<?php
/**
 * Created by PhpStorm.
 * User: phpzh
 * Date: 2020/6/5
 * Time: 10:15
 */

namespace app\api\controller;


use think\Cache;
use think\Controller;
use app\common\lib\exception\ApiException;
use app\common\lib\Aes;
use app\common\lib\IAuth;

/**
 * API模块，公共的控制器
 * Class Common
 * @package app\api\controller
 */
class Common extends Controller
{
    /**
     * header 头
     * @var string
     */
    public $headers = '';

    public $page = 1;
    public $size = 10;
    public $from = 0;

    /**
     * 初始化的方法
     */
    public function _initialize()
    {
        $this->checkRequestAuth();
        //$this->testAes();
    }

    /***
     * 检查每次app请求的数据是否合法
     */
    public function checkRequestAuth()
    {
        //首先需要获取headers
        $headers = request()->header();
        //基础参数校验
        if (empty($headers['sign'])) {
            throw new ApiException('sign不存在', 400);
        }
        if (!in_array($headers['apptype'], config('app.apptypes'))) {
            throw new ApiException('类型不合法', 400);
        }
//        $data
//        if (!IAuth::checkSignPass($headers)) {
//            throw new ApiException('授权码sign失败', 401);
//        }
        Cache::set($headers['sign'], 1, config('app.app_sign_cache_time'));
        $this->headers = $headers;
    }

    public function testAes()
    {
        $str = "id=1&ms=45&username=singwa";
        echo (new Aes())->encrypt($str);
        exit();
    }

    /***
     * 获取处理新闻的数据
     * @param array $news
     */
    protected function getDealNews($news = [])
    {
        if (empty($news)) {
            return [];
        }

        $cats = config('cat.lists');

        foreach ($news as $key => $new) {
            $news[$key]['catname'] = $cats[$new['catid']] ? $cats[$new['catid']] : '-';
        }

        return $news;
    }


    /**
     * 获取分页page size 内容
     */
    public function getPageAndSize($data)
    {
        $this->page = !empty($data['page']) ? $data['page'] : 1;
        $this->size = !empty($data['size']) ? $data['size'] : config('paginate.list_rows');
        $this->from = ($this->page - 1) * $this->size;
    }
}